package com.project.controller.base;

import com.project.util.Util;
import com.project.util.View;
import com.project.util.encode.AES256;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;

@Controller
public class BaseController {
    @Value("${spring.profiles.active}")
    String env;
    @Value("${app.key}")
    protected String appKey;

    protected String titleSuffix = "Spring Boot中文社区";
    protected String pageKey = "java,spring boot,java论坛,spring boot论坛,java社区,spring boot社区,spring boot教程,java教程,spring boot视频,spring开源,java新手,java,spring boot";
    protected String pageDesc = "我们是高品质的 spring boot 开发者社区，致力于为 spring 和 java 开发者提供一个分享创造、结识伙伴、协同互助的论坛。";

    /**
     * 控制器前置操作，把值传递到所有的页面
     *
     * @param model
     */
    @ModelAttribute
    public void before(Model model, HttpServletRequest request) {
        model.addAttribute("env", env);
        String csrfToken = getAndGenerateCsrfToken(request);
        model.addAttribute("_csrfToken", csrfToken);
        model.addAttribute("_view", new View());
    }

    @ModelAttribute
    public void tdk(Model model, HttpServletRequest request) {
        model.addAttribute("titleSuffix", titleSuffix);
        model.addAttribute("pageKey", pageKey);
        model.addAttribute("pageDesc", pageDesc);
    }

    /**
     * 生成csrfToken
     *
     * @param request
     * @return
     */
    private String getAndGenerateCsrfToken(HttpServletRequest request) {
        String seed = Util.getFormatDate("yyyy-MM-dd") + appKey;
        String csrfToken = DigestUtils.sha256Hex(seed);
        request.getSession().setAttribute("X-CSRF-TOKEN", csrfToken);
        return csrfToken;
    }
}